package com.ikaros.api;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ikaros.dao.RegionDao;
import com.ikaros.entity.Region;

/**
 * @author: 胡国军
 * @Date 2018-01-06 19:01
 */
@Service("createRegion")
public class CreateRegion {

    @Autowired
    private RegionDao regionDao;

    public void createProvince(){
        try {
            File xlsFile = new File("E://广州.xlsx");
            // 获得工作簿
            Workbook workbook = WorkbookFactory.create(xlsFile);
            // 获得工作表个数
            int sheetCount = workbook.getNumberOfSheets();
            List<Region> regionList=new ArrayList<>();
            Region region=null;
            // 遍历工作表
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                // 获得行数
                int rows = sheet.getLastRowNum() + 1;
                // 获得列数，先获得一行，在得到改行列数
                Row tmp = sheet.getRow(0);
                if (tmp == null) {
                    continue;
                }
                int cols = tmp.getPhysicalNumberOfCells();
                // 读取数据
                for (int row = 0; row < rows; row++) {
                    Row r = sheet.getRow(row);
                    Cell cell = r.getCell(1);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    System.out.println(cell.getStringCellValue());
                    Cell gbCode = r.getCell(6);
                    gbCode.setCellType(Cell.CELL_TYPE_STRING);
                    String code = gbCode.getStringCellValue();
                    Region diffentRegion = this.getDiffentRegion(regionList, cell.getStringCellValue(), 0,"0",1,code.substring(0,3));
                    if (diffentRegion!=null){
                        regionList.add(diffentRegion);
                    }
                }
            }
            List<Region> save = regionDao.save(regionList);
            for (Region r : save) {
                r.setPath(r.getPath() + "/" + r.getId());
            }
            regionDao.save(save);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void createCity(){
        try {
            File xlsFile = new File("E://广州.xlsx");
            // 获得工作簿
            Workbook workbook = WorkbookFactory.create(xlsFile);
            // 获得工作表个数
            int sheetCount = workbook.getNumberOfSheets();
            List<Region> regionList=new ArrayList<>();
            Region region=null;
            // 遍历工作表
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                // 获得行数
                int rows = sheet.getLastRowNum() + 1;
                // 获得列数，先获得一行，在得到改行列数
                Row tmp = sheet.getRow(0);
                if (tmp == null) {
                    continue;
                }
                int cols = tmp.getPhysicalNumberOfCells();
                // 读取数据
                for (int row = 0; row < rows; row++) {
                    Row r = sheet.getRow(row);
                    //市区
                    Cell cell = r.getCell(1);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    System.out.println(cell.getStringCellValue());
                    Cell gbCode = r.getCell(5);
                    gbCode.setCellType(Cell.CELL_TYPE_STRING);
                    String code = gbCode.getStringCellValue();
                    Cell sheng = r.getCell(0);
                    gbCode.setCellType(Cell.CELL_TYPE_STRING);
                    String shengName = sheng.getStringCellValue();
                    List<Region> byName = regionDao.findByName(shengName);
                    Region diffentRegion = this.getDiffentRegion(regionList, cell.getStringCellValue(),byName.get(0).getId(), byName.get(0).getPath(),2,code.substring(0,4));
                    if (diffentRegion!=null){
                        regionList.add(diffentRegion);
                    }
                }
            }
            List<Region> save = regionDao.save(regionList);
            for (Region r : save) {
                r.setPath(r.getPath() + "/" + r.getId());
                System.out.println(r.getPath());
            }
            regionDao.save(save);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void createArea(){
        try {
            File xlsFile = new File("E://广州.xlsx");
            // 获得工作簿
            Workbook workbook = WorkbookFactory.create(xlsFile);
            // 获得工作表个数
            int sheetCount = workbook.getNumberOfSheets();
            List<Region> regionList=new ArrayList<>();
            Region region=null;

            // 遍历工作表
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                // 获得行数
                int rows = sheet.getLastRowNum() + 1;
                // 获得列数，先获得一行，在得到改行列数
                Row tmp = sheet.getRow(0);
                if (tmp == null) {
                    continue;
                }
                int cols = tmp.getPhysicalNumberOfCells();
                // 读取数据
                for (int row = 0; row < rows; row++) {
                    Row r = sheet.getRow(row);
                    //市区
                    Cell cell = r.getCell(2);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    System.out.println(cell.getStringCellValue());
                    Cell gbCode = r.getCell(5);
                    gbCode.setCellType(Cell.CELL_TYPE_STRING);
                    String code = gbCode.getStringCellValue();
                    Cell shi = r.getCell(1);
                    gbCode.setCellType(Cell.CELL_TYPE_STRING);
                    String shiName = shi.getStringCellValue();
                    List<Region> byName = regionDao.findByName(shiName);
                    if (!byName.get(0).getName().equals(cell.getStringCellValue())){
                        Region diffentRegion = this.getDiffentRegion(regionList, cell.getStringCellValue(),byName.get(0).getId(), byName.get(0).getPath(),3,code);
                        if (diffentRegion!=null){
                            regionList.add(diffentRegion);
                        }
                    }
                }
            }
            List<Region> save = regionDao.save(regionList);
            for (Region r : save) {
                r.setPath(r.getPath() + "/" + r.getId());
            }
            regionDao.save(save);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Region getDiffentRegion(List<Region> regions,String regionName,int parentId,String path,Integer level,String code){
        for (Region region:regions){
            if (region.getName().equals(regionName)){
                return null;
            }
        }
        Region region = new Region();
        region.setName(regionName);
        region.setParentId(parentId);
        region.setSort(regions.size()+1);
        region.setLevel(level);
        region.setPath(path);
        region.setGbCode(code);
        return region;
    }

    private Region getDifferentArea(List<Region> regions,String regionName,int parentId,String path,Integer level,String code){
        for (Region region:regions){
            if (region.getName().equals(regionName)){
                return null;
            }
        }
        Region region = new Region();
        region.setName(regionName);
        region.setParentId(parentId);
        region.setLevel(level);
        region.setPath(path);
        region.setGbCode(code);
        return region;
    }

    public void paiduAPI() {
        List<Region> regionList = regionDao.findAll();
        for (Region region : regionList) {
            Region one = regionDao.findOne(region.getParentId());
            try {
                Map paramsMap = new LinkedHashMap<String, String>();
                if (one!=null){
                    paramsMap.put("address", one.getName()+region.getName());
                }else {
                    paramsMap.put("address", region.getName());
                }
                paramsMap.put("output", "json");
                paramsMap.put("ak", "vInhpg2WvEB9AOA40GX1kWdMwmOP6tD9");

                // 调用下面的toQueryString方法，对LinkedHashMap内所有value作utf8编码，拼接返回结果address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourak
                String paramsStr = this.toQueryString(paramsMap);

                // 对paramsStr前面拼接上/geocoder/v2/?，后面直接拼接yoursk得到/geocoder/v2/?address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourakyoursk
                String wholeStr = new String("/geocoder/v2/?" + paramsStr);

                // 对上面wholeStr再作utf8编码
                String location = this.getLocation(wholeStr);
                System.out.println(location);
                JSONObject parse = (JSONObject) JSONObject.parse(location);
                JSONObject result = (JSONObject) parse.get("result");
                JSONObject JSONObject = (JSONObject) result.get("location");
                String latBaiDu = String.valueOf(JSONObject.get("lat"));
                String lat = latBaiDu.substring(0,latBaiDu.indexOf(".")+6);
                String lngBaiDu = String.valueOf(JSONObject.get("lng"));
                String lng = lngBaiDu.substring(0,lngBaiDu.indexOf(".")+6);
                region.setMapAddress(lat + "," + lng);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        regionDao.save(regionList);
    }

    public String getLocation(String url) {

        String urlNameString = "http://api.map.baidu.com/" + url;
        String result = "";
        try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(urlNameString);//这里发送get请求
            // 获取当前客户端对象
            HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
        //....result是用户信息,站内业务以及具体的json转换这里也不写了...
    }

    private String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Map.Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }
}
